<template>
  <div class="smsEditor">
    <div class="cont-top">
      <el-button @click="insertClientAttr">插入客户属性</el-button>
      <el-button :disabled="!shortLinkFlag" @click="insertShortLink">插入短连接</el-button>
    </div>
    <!-- 加载编辑器的容器 -->
    <script :id="editorId" name="content" type="text/plain">
    </script>
    <el-dialog
      title="插入客户属性"
      :visible.sync="dialogClientAttr"
      width="30%">
      <div class="clientAttrWrap">
        <el-select v-model="clientAttrObj" filterable placeholder="请选择" clearable @change="getclientAttr">
          <el-option
            v-for="item in clientAttrList"
            :key="item.value"
            :label="item.label"
            :value="item">
          </el-option>
        </el-select>
        <h4 class="">属性为空时显示：</h4>
        <el-input v-model="clientAttrEmpty" placeholder=""></el-input>
        <el-button type="primary" style="width:100px" @click="sureClientAttr()">确 认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="插入短链接"
      :visible.sync="dialogShortLink"
      width="30%">
      <el-form class="clientAttrWrap" :rules="rules" ref="linkForm" :model="linkForm">
        <h4 class="">输入链接：</h4>
        <el-form-item label="" prop="shortLink">
          <el-input v-model="linkForm.shortLink" placeholder=""></el-input>
        </el-form-item>
        <el-button type="primary" style="width:100px" @click="sureShortLink('linkForm')">确 认</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import '@static/ueditor/ueditor.config'
  import '@static/ueditor/ueditor.all'
  import '@static/ueditor/lang/zh-cn/zh-cn'
  import {mapState, mapActions, mapMutations} from 'vuex'
  export default {
    data () {
      return {
        editorId: 'smsEditorContainer',
        dialogClientAttr: false,
        clientAttrObj: {},
        clientAttr: '',
        clientAttrName: '',
        clientAttrEmpty: '',
        dialogShortLink: false,
        shortLinkFlag: true,
        linkForm: {
          shortLink: ''
        },
        rules: {
          shortLink: [{required: true, message: '请输入链接', trigger: 'blur'},
            {pattern: /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/, message: '请输入正确的链接', trigger: 'blur'}]
        }
      }
    },
    mounted () {
      window.ue && window.ue.destroy()
      this.initEditor()
    },
    props: ['content'],
    watch: {
      'content': function (now) {
        this.setContent(now)
      }
    },
    computed: {
      ...mapState({
        viewCont: state => state.contentManage.smsViewCont,
        clientAttrMap: state => state.contentManage.clientAttrMap
      }),
      clientAttrList () {
        let arr = []
        for (let key in this.clientAttrMap) {
          arr.push({value: key, label: this.clientAttrMap[key]})
        }
        return arr
      }
    },
    methods: {
      ...mapActions(['setShortLink']),
      ...mapMutations(['SET_SMS_VIEWCONT']),
      // 初始化编辑器
      initEditor () {
        let me = this
        window.ue = this.ue = UE.getEditor(this.editorId, {
          toolbars: [],
          initialFrameWidth: 630,
          initialFrameHeight: 158,
          minFrameWidth: 770,
          minFrameHeight: 300,
          allHtmlEnabled: true,
          scaleEnabled: false,
          elementPathEnabled: false,
          wordCount: true,
          maximumWords: 65,
          autoFloatEnabled: false
        })
        this.ue.addInputRule(function (root) {
          root.getNodesByTagName('img').forEach(node => {
            const src = node.getAttr('data-src') || node.getAttr('_src')
            node.setAttr('src', src)
          })
        })
        this.ue.addListener('contentChange', () => {
          this.SET_SMS_VIEWCONT(this.ue.getContent().replace(/\$\{\s*([^#]+)\s*#.*?\}/g, (match, key) => {
            return me.clientAttrMap[key]
          }))
          this.$emit('contentChange', this.ue.getContent())
        })
        this.ue.addListener('keydown', function (type, event) {
          let range = me.ue.selection.getRange()
          let aStart = UE.dom.domUtils.findParentByTagName(range.startContainer, 'a', true)
          if (event.keyCode === 8 || event.keyCode === 46) {
            if (aStart && (UE.dom.domUtils.hasClass(aStart, 'insert_client_attr') || UE.dom.domUtils.hasClass(aStart, 'insert_short_link'))) {
              if (UE.dom.domUtils.hasClass(aStart, 'insert_short_link')) {
                me.shortLinkFlag = true
              }
              UE.dom.domUtils.remove(aStart)
              me.SET_SMS_VIEWCONT(me.ue.getContent().replace(/\$\{\s*([^#]+)\s*#.*?\}/g, (match, key) => {
                return me.clientAttrMap[key]
              }))
              event.preventDefault()
            }
          }
          // else if (event.keyCode === 46) {
            // console.log(range)
            // console.log(range.endContainer.nextElementSibling)
            // let range = me.ue.selection.getRange()
            // let aEnd = UE.dom.domUtils.findParentByTagName(range.endContainer, 'a', true)
            // if (aEnd && (UE.dom.domUtils.hasClass(aEnd, 'insert_client_attr') || UE.dom.domUtils.hasClass(aEnd, 'insert_short_link'))) {
            //   UE.dom.domUtils.remove(aEnd)
            //   event.preventDefault()
            // }
          // }
        })
        // this.ue.addListener('focus', () => {
        //   // let range = me.ue.selection.getRange()
        //   // // let aStart = UE.dom.domUtils.findParentByTagName(range.startContainer, 'a', true)
        //   // console.log(range)
        // })
      },
      execCommand (command, str) {
        this.ue.execCommand(command, str)
      },
      setContent (cont) {
        this.shortLinkFlag = !(cont.indexOf('class="insert_short_link"') >= 0)
        if (!this.ue.isReady) {
          this.ue.addListener('ready', () => {
            this.ue.setContent(cont)
          })
        } else {
          this.ue.setContent(cont)
        }
      },
      getEditorCont () {
        return this.ue.getContent()
      },
      // 插入客户属性按钮
      insertClientAttr () {
        this.dialogClientAttr = true
      },
      // 确认插入客户属性 &#8203;
      sureClientAttr () {
        let insertCont = '<a class="insert_client_attr" href="javascript:;">${' + this.clientAttr + '#' + this.clientAttrEmpty + '}</a>'
        if (this.clientAttr === '') {
          this.$message({
            type: 'warning',
            message: '请选择客户属性'
          })
        } else {
          this.ue.execCommand('insertHtml', insertCont)
          this.setContent(this.ue.getContent().replace(/^&#8203;$/g, ''))
          this.dialogClientAttr = false
          this.clientAttrObj = {}
          this.clientAttr = ''
          this.clientAttrName = ''
          this.clientAttrEmpty = ''
        }
      },
      getclientAttr () {
        this.clientAttrName = this.clientAttrObj.label
        this.clientAttr = this.clientAttrObj.value
      },
      // 插入短链接
      insertShortLink () {
        this.linkForm.shortLink = ''
        this.dialogShortLink = true
      },
      // 确认插入短链接
      sureShortLink (form) {
        let me = this
        me.$refs[form].validate(valid => {
          if (valid) {
            me.setShortLink({url: me.linkForm.shortLink})
              .then(res => {
                if (res.data.code === 1) {
                  let insertCont = '<a class="insert_short_link" href="' + res.data.data + '">' + res.data.data + '&#8203;</a>'
                  me.ue.execCommand('insertHtml', insertCont)
                  setTimeout(() => {
                    me.setContent(me.ue.getContent().replace(/^&#8203;$/g, ''))
                  }, 100)
                  me.dialogShortLink = false
                  me.shortLinkFlag = false
                  me.ue.focus(true)
                }
              })
          }
        })
      }
    }
  }
</script>
<style lang="scss">
  .smsEditor{
    line-height: 18px;
    position:relative;
    max-height: 285px;
    overflow: scroll;
    .cont-top{
      position: absolute;
      top: 1px;
      left: 1px;
      z-index: 1000;
      padding: 8px 0 8px 30px;
      width: 599px;
      border-bottom: 1px solid #d4d4d4;
    }
    .edui-editor-iframeholder{
      margin:50px 0 50px 0;
      padding-top:1px;
    }
  }

  .clientAttrWrap{
    text-align: center;
    .el-select{width: 100%;}
    h4{
      margin-top: 20px;
      margin-bottom: 5px;
      text-align: left;
      font-weight: normal;
    }
    .el-form-item {
      width: 100%;
    }
    .el-button{
      margin-top: 30px;
    }
  }
</style>
